package com.yuntoyun.fwcore.util;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import android.content.Context;
import android.os.Environment;
import android.os.storage.StorageManager;

import com.yuntoyun.fwcore.base.FwApplication;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 硬件检测工具类
 */
public class FwSDCardUtil {

    private static FwSDCardUtil init = null;

    public static FwSDCardUtil builder() {
        if (null == init) {
            init = new FwSDCardUtil();
        }
        return init;
    }

    /**
     * 检测是否存在SDCard（扩展卡)
     *
     * @return
     */
    public boolean isSDCardEnableByEnvironment() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * 获取SDCard根目录
     *
     * @return
     */
    public String getSDCardPathByEnvironment() {
        if (isSDCardEnableByEnvironment()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return "";
    }

    /**
     * SDCard是否存在
     *
     * @return
     */
    public boolean isSDCardEnableByService() {
        return !getSDCardPaths().isEmpty();
    }

    /**
     * 获取所有SDCard的根目录
     *
     * @param removable （是否为可拆御）
     * @return
     */
    public List<String> getSDCardPaths(final boolean removable) {
        List<String> paths = new ArrayList<>();
        StorageManager sm =
                (StorageManager) FwApplicationUtil.appContext().getSystemService(Context
                        .STORAGE_SERVICE);
        try {
            Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            //noinspection JavaReflectionMemberAccess
            Method getVolumeList = StorageManager.class.getMethod("getVolumeList");
            //noinspection JavaReflectionMemberAccess
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            Object result = getVolumeList.invoke(sm);
            final int length = Array.getLength(result);
            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                String path = (String) getPath.invoke(storageVolumeElement);
                boolean res = (Boolean) isRemovable.invoke(storageVolumeElement);
                if (removable == res) {
                    paths.add(path);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return paths;
    }

    /**
     * 获取所有SDCard的根目录
     *
     * @return
     */
    public List<String> getSDCardPaths() {
        StorageManager storageManager = (StorageManager) FwApplicationUtil.appContext()
                .getSystemService(Context.STORAGE_SERVICE);
        List<String> paths = new ArrayList<>();
        try {
            //noinspection JavaReflectionMemberAccess
            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths");
            getVolumePathsMethod.setAccessible(true);
            Object invoke = getVolumePathsMethod.invoke(storageManager);
            paths = Arrays.asList((String[]) invoke);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return paths;
    }

    /**
     * 获取SDCard的可用根目录
     *
     * @return
     */
    public String getRootPath() {
        StringBuilder sb = new StringBuilder("");
        if (isSDCardEnableByEnvironment()) {
            // filePath:/sdcard/ 或 /storage/emulated/0/
            sb.append(FwPathUtil.getExternalStoragePath() + FwPathUtil.FILE_SEP);
        } else {
            // filePath: /data/data/
            sb.append(FwPathUtil.getDataPath());
            sb.append(FwPathUtil.FILE_SEP);
            sb.append("data");
            sb.append(FwPathUtil.FILE_SEP);
        }
        return sb.toString();
    }

    /**
     * 获取SDCard的可用根目录
     *
     * @return
     */
    public String getAppRootPath() {
        StringBuilder sb = new StringBuilder("");
        sb.append(getRootPath());
        sb.append(FwApplicationUtil.builder().getAppPackageName());
        sb.append(FwPathUtil.FILE_SEP);
        return sb.toString();
    }

    /**
     * 自定义应用目录
     *
     * @param dirName
     * @return
     */
    public String getCustomePath(String dirName) {
        StringBuilder sb = new StringBuilder("");
        sb.append(getAppRootPath());
        sb.append(dirName);
        sb.append(FwPathUtil.FILE_SEP);
        boolean created = FwFileUtil.builder().createOrExistsDir(sb.toString());
        return (created) ? sb.toString() : "";
    }
}
